extends CharacterBody2D
class_name Enemy01


const SPEED = 30.0
const HIT_VELOCITY_Y = -100.0
const HIT_VELOCITY_X = 70.0
const ATTACK_DISTANCE = 25
const CHASE_DISTANCE = 70
@export var acceleration = 300

# Get the gravity from the project settings to be synced with RigidBody nodes.
var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")
var gravityScale = 0.5

var player:PlayerScript
var stateMachine:StateMachine
var animations:AnimationPlayer
var weaponAnimations:AnimationPlayer
var enemySpriteRoot

@onready var enemySprite = $EnemySpriteRoot/EnemyRotParent/Sprite2D
@onready var animationPlayerShader = $AnimationPlayerShader


var health = 3
var damage = 5


func _ready():
	add_to_group("Enemy")
	
	player = get_tree().get_first_node_in_group("Player") as PlayerScript
	enemySpriteRoot = $EnemySpriteRoot
	animations = $AnimationPlayer
	weaponAnimations = $WeaponAnimationPlayer
	
	stateMachine = get_node("StateMachine") as StateMachine
	stateMachine.changeState("StateIdle", self)


func _physics_process(delta):
	stateMachine.physicsProcess(delta, self)
	

func _process(delta):
	(stateMachine as StateMachine).process(delta, self)
	

func onHit(attacker:Node2D):
	print("onhit" + attacker.name)
	Global.createHitEffect(global_position + Vector2(0, -8) + GlobalUtils.vector2RandomRange(5, 5), get_tree().current_scene)
	
	health -= attacker.damage
	stateMachine.changeState("StateHit", self)
	
	if health <= 0:
		attacker.gainExp(Global.enemyExpConfig["E01"])
		if randf() <= 0.5:
			Global.createCorn(self.global_position, get_tree().current_scene)
	

func _on_club_hit_area_body_entered(body):
	if body.is_in_group("Player"):
		body.onHit(self)
		

func setHitFlashWhite():
	enemySprite.material.set_shader_parameter("active", true)
	

func setHitFlashOrigin():
	enemySprite.material.set_shader_parameter("active", false)
	
	
func die():
	queue_free()
	
